package com.hunttown.mes.manage.controller._mes;

import com.hunttown.mes.common.utils.DateConvertUtils;
import com.hunttown.mes.common.utils.DateUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.manage.controller.common.ModelService;
import com.hunttown.mes.manage.service.MesProduceOrderManageService;
import com.hunttown.mes.manage.service.MesSaleOrderManageService;
import com.hunttown.mes.manage.service.TransportPurchaseDetailManageService;
import com.hunttown.mes.rpc.domain.MesProduceOrderDTO;
import com.hunttown.mes.rpc.domain.query.MesProduceOrderDTOQuery;
import com.hunttown.mes.rpc.domain.query.MesSaleOrderDTOQuery;
import com.hunttown.common.domain.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @title: 统计图表
 * @author: wangjunfu
 * @date: 2022年07月25日 9:10
 * @description:
 */
@Controller
@RequestMapping(value = "/mes/charts")
public class MesChartsController {

    private final static Logger logger = LoggerFactory.getLogger(MesChartsController.class);

    private final MesSaleOrderManageService mesSaleOrderService;
    private final MesProduceOrderManageService mesProduceOrderService;
    private final TransportPurchaseDetailManageService purchaseDetailService;
    private final ModelService modelService;

    @Autowired
    public MesChartsController(MesSaleOrderManageService mesSaleOrderService, MesProduceOrderManageService mesProduceOrderService, TransportPurchaseDetailManageService purchaseDetailService, ModelService modelService) {
        this.mesSaleOrderService = mesSaleOrderService;
        this.mesProduceOrderService = mesProduceOrderService;
        this.purchaseDetailService = purchaseDetailService;
        this.modelService = modelService;
    }

    //region 主页门户

    /**
     * 主页门户
     *
     * @param model model
     * @return vm
     */
    @RequestMapping(value = "/homePage", method = RequestMethod.GET)
    public String homePage(Model model) {
        model.addAttribute("title", "门户");
        return "mes/charts/home-page";
    }
    //endregion

    //region 异步获取数据集合

    //region 7个统计选项卡

    /**
     * 7个统计选项卡
     *
     * @param key 标识
     * @return map
     */
    @RequestMapping(value = "/getStatistic", method = RequestMethod.POST)
    @ResponseBody
    public Map<Object, Object> getStatistic(String key) {
        Map<Object, Object> map = new HashMap<>();
        map.put("returnCode", 0);

        //总销售订单
        if (key.equals("total_sale_order")) {
            MesSaleOrderDTOQuery query = new MesSaleOrderDTOQuery();
            Long count = mesSaleOrderService.countByQuery(query);
            map.put("number", count);
        }

        //总生产订单
        if (key.equals("total_produce_order")) {
            MesProduceOrderDTOQuery query = new MesProduceOrderDTOQuery();
            Long count = mesProduceOrderService.countByQuery(query);
            map.put("number", count);
        }

        //今年销售订单
        if (key.equals("year_sale_order")) {
            MesSaleOrderDTOQuery query = new MesSaleOrderDTOQuery();
            query.setYearOnly(DateUtils.getCurrYear());
            Long count = mesSaleOrderService.countByQuery(query);
            map.put("number", count);
        }

        //今年生产订单
        if (key.equals("year_produce_order")) {
            MesProduceOrderDTOQuery query = new MesProduceOrderDTOQuery();
            query.setYearOnly(DateUtils.getCurrYear());
            Long count = mesProduceOrderService.countByQuery(query);
            map.put("number", count);
        }

        //本月销售订单
        if (key.equals("month_sale_order")) {
            MesSaleOrderDTOQuery query = new MesSaleOrderDTOQuery();
            query.setYearMonth(DateUtils.getCurrYearMonth());
            Long count = mesSaleOrderService.countByQuery(query);
            map.put("number", count);
        }

        //本月生产订单
        if (key.equals("month_produce_order")) {
            MesProduceOrderDTOQuery query = new MesProduceOrderDTOQuery();
            query.setYearMonth(DateUtils.getCurrYearMonth());
            Long count = mesProduceOrderService.countByQuery(query);
            map.put("number", count);
        }

        //在产生产订单
        if (key.equals("online_produce_order")) {
            MesProduceOrderDTOQuery query = new MesProduceOrderDTOQuery();
            query.setAfterStatus(0);
            query.setBeforeStatus(15);
            Long count = mesProduceOrderService.countByQuery(query);
            map.put("number", count);
        }

        map.put("returnCode", 1);
        return map;
    }
    //endregion

    //region 根据不同的业务获取不同的数据

    /**
     * 根据不同的业务获取不同的数据
     *
     * @param model    model
     * @param key      业务标识key
     * @param template 模板
     * @return vm
     */
    @RequestMapping(value = "/getStatisticData", method = RequestMethod.POST)
    public String getStatisticData(Model model, String key, String template) {

        //日销售、生产订单
        if (key.equals("daySaleOrder")) {
            getDaySaleOrder(model);
        }

        //月销售、生产订单
        if (key.equals("monthSaleOrder")) {
            getMonthSaleOrder(model);
        }

        //在产订单耗时
        if (key.equals("onlineOrder")) {
            getOnlineOrder(model);
        }

        //良品率
        if (key.equals("goodRate")) {
            getGoodRate(model);
        }

        //用料TOP20
        if (key.equals("meterialTop20")) {
            getMeterialTop(model);
        }

        model.addAttribute("divId", key);
        return "echarts/" + template;
    }
    //endregion

    //region （子）日销售、生产订单
    private void getDaySaleOrder(Model model) {
        model.addAttribute("divHeight", "280px");
        model.addAttribute("chartTitle", "订单折线图");

        List<String> legend = new ArrayList<>();
        legend.add("销售订单");
        legend.add("生产订单");
        model.addAttribute("chartLegend", legend);


        //存储x轴、存储y轴
        List<String> x_Axis = DateUtils.getDayList(15, DateConvertUtils.getPastDate(0));
        List<List<String>> y_Axis = new ArrayList<>();

        //15天销售数据
        MesSaleOrderDTOQuery saleQuery = new MesSaleOrderDTOQuery();
        saleQuery.setStartDate(x_Axis.get(0));
        saleQuery.setEndDate(x_Axis.get(x_Axis.size() - 1));
        List<Map<String, String>> saleMap = mesSaleOrderService.getMapDataByQuery(saleQuery, "selectSaleCountByDay");

        //15天生产数据
        MesProduceOrderDTOQuery produceQuery = new MesProduceOrderDTOQuery();
        produceQuery.setStartDate(x_Axis.get(0));
        produceQuery.setEndDate(x_Axis.get(x_Axis.size() - 1));
        List<Map<String, String>> produceMap = mesProduceOrderService.getMapDataByQuery(produceQuery, "selectProduceCountByDay");

        List<String> temp_sale = new ArrayList<>();
        List<String> temp_produce = new ArrayList<>();

        for (String day : x_Axis) {
            //销售数据
            int has = 0;
            for (Map<String, String> map : saleMap) {
                Object dt = map.get("dayDate");
                if (dt == null) {
                    continue;
                }

                if (dt.toString().equals(day)) {
                    temp_sale.add(map.get("num"));
                    has = 1;
                }
            }

            if (has == 0) {
                temp_sale.add("0");
            }

            //订单数据
            has = 0;
            for (Map<String, String> map : produceMap) {
                Object dt = map.get("dayDate");
                if (dt == null) {
                    continue;
                }

                if (dt.toString().equals(day)) {
                    temp_produce.add(map.get("num"));
                    has = 1;
                }
            }

            if (has == 0) {
                temp_produce.add("0");
            }
        }

        //Collections.reverse(x_Axis);
        //Collections.reverse(temp_sale);  //反转
        //Collections.reverse(temp_produce);  //反转

        y_Axis.add(temp_sale);
        y_Axis.add(temp_produce);

        model.addAttribute("xAxis", x_Axis);
        model.addAttribute("yAxis", y_Axis);
    }
    //endregion

    //region （子）月销售、生产订单
    private void getMonthSaleOrder(Model model) {
        List<String> legend = new ArrayList<>();
        legend.add("销售订单");
        legend.add("生产订单");
        model.addAttribute("chartLegend", legend);


        //存储x轴、存储y轴
        List<String> x_Axis = DateUtils.getMonthList(12, DateConvertUtils.getPastDate(0));
        List<List<String>> y_Axis = new ArrayList<>();

        //12个月销售数据
        MesSaleOrderDTOQuery saleQuery = new MesSaleOrderDTOQuery();
        saleQuery.setStartYearMonth(x_Axis.get(0));
        saleQuery.setEndYearMonth(x_Axis.get(x_Axis.size() - 1));
        List<Map<String, String>> saleMap = mesSaleOrderService.getMapDataByQuery(saleQuery, "selectSaleCountByMonth");

        //12个月生产数据
        MesProduceOrderDTOQuery produceQuery = new MesProduceOrderDTOQuery();
        produceQuery.setStartYearMonth(x_Axis.get(0));
        produceQuery.setEndYearMonth(x_Axis.get(x_Axis.size() - 1));
        List<Map<String, String>> produceMap = mesProduceOrderService.getMapDataByQuery(produceQuery, "selectProduceCountByMonth");

        List<String> temp_sale = new ArrayList<>();
        List<String> temp_produce = new ArrayList<>();

        for (String day : x_Axis) {
            //销售数据
            int has = 0;
            for (Map<String, String> map : saleMap) {
                Object dt = map.get("monthDate");
                if (dt == null) {
                    continue;
                }

                if (dt.toString().equals(day)) {
                    temp_sale.add(map.get("num"));
                    has = 1;
                }
            }

            if (has == 0) {
                temp_sale.add("0");
            }

            //订单数据
            has = 0;
            for (Map<String, String> map : produceMap) {
                Object dt = map.get("monthDate");
                if (dt == null) {
                    continue;
                }

                if (dt.toString().equals(day)) {
                    temp_produce.add(map.get("num"));
                    has = 1;
                }
            }

            if (has == 0) {
                temp_produce.add("0");
            }
        }

        y_Axis.add(temp_sale);
        y_Axis.add(temp_produce);

        model.addAttribute("xAxis", x_Axis);
        model.addAttribute("yAxis", y_Axis);
    }
    //endregion

    //region （子）在产订单耗时
    private void getOnlineOrder(Model model) {
        model.addAttribute("chartTitle", "在产订单耗时");

        List<String> legend = new ArrayList<>();
        legend.add("耗时（小时）");
        model.addAttribute("chartLegend", legend);

        //存储x轴、存储y轴
        List<String> x_Axis = new ArrayList<>();
        List<List<String>> y_Axis = new ArrayList<>();

        //获取所有在产订单
        MesProduceOrderDTOQuery produceQuery = new MesProduceOrderDTOQuery();
        produceQuery.setStatus(12);
        produceQuery.setStopFlag(0);
        produceQuery.setOrderBy("order by start_time asc");
        Page<MesProduceOrderDTO> dataPage = mesProduceOrderService.getForPage(produceQuery);

        String default_date = DateConvertUtils.dateToStr(new Date());
        List<String> temp_produce = new ArrayList<>();
        for (MesProduceOrderDTO item : dataPage.getItems()) {
            x_Axis.add(item.getOrderName());

            Long diff = DateUtils.getDistanceHour(item.getStartTimeSr(), default_date);
            temp_produce.add(diff + "");
        }

        y_Axis.add(temp_produce);

        model.addAttribute("xAxis", x_Axis);
        model.addAttribute("yAxis", y_Axis);
    }
    //endregion

    //region （子）良品率
    private void getGoodRate(Model model) {
        model.addAttribute("chartTitle", "良品率");

        List<String> legend = new ArrayList<>();
        legend.add("良品率");
        model.addAttribute("chartLegend", legend);

        //存储x轴、存储y轴
        List<String> x_Axis = new ArrayList<>();
        List<List<String>> y_Axis = new ArrayList<>();

        //最新20条已完成订单
        MesProduceOrderDTOQuery produceQuery = new MesProduceOrderDTOQuery();
        produceQuery.setAfterStatus(20);
        produceQuery.setStopFlag(0);
        produceQuery.setPageSize(20);
        produceQuery.setOrderBy("order by id desc");
        Page<MesProduceOrderDTO> dataPage = mesProduceOrderService.getForPage(produceQuery);

        List<String> temp_produce = new ArrayList<>();
        for (MesProduceOrderDTO item : dataPage.getItems()) {
            x_Axis.add("订单" + item.getId());
            temp_produce.add(item.getGoodRate() + "");
        }

        y_Axis.add(temp_produce);

        model.addAttribute("xAxis", x_Axis);
        model.addAttribute("yAxis", y_Axis);
    }
    //endregion

    //region （子）用料TOP2
    private void getMeterialTop(Model model) {
        model.addAttribute("chartTitle", "用料");
        model.addAttribute("xRotate", 40);

        List<String> legend = new ArrayList<>();
        legend.add("用料");
        model.addAttribute("chartLegend", legend);

        //存储x轴、存储y轴
        List<String> x_Axis = new ArrayList<>();
        List<List<String>> y_Axis = new ArrayList<>();

        //用料TOP20
        List<Map<String, String>> meterialMap = purchaseDetailService.getMeterialTop20();

        List<String> temp_metetrial = new ArrayList<>();

        for (Map<String, String> map : meterialMap) {
            Object pId = map.get("partId");
            if (pId == null) {
                continue;
            }

            String pName = modelService.getPurchaseName(Integer.parseInt(pId + ""));
            if (StringUtils.isBlank(pName)) {
                continue;
            }

            x_Axis.add(pName);
            temp_metetrial.add(map.get("num"));
        }

        y_Axis.add(temp_metetrial);

        model.addAttribute("xAxis", x_Axis);
        model.addAttribute("yAxis", y_Axis);
    }
    //endregion

    //endregion
}
